//
//  VPreviewVC.m
//  VChatVideoClip
//
//  Created by huangbolun on 2017/10/10.
//  Copyright © 2017年 huangbolun. All rights reserved.
//

#import "VPreviewVC.h"
#import <AVFoundation/AVFoundation.h>
#import "VClipIndicatorView.h"
#import "VVideoClipManger.h"
#import "VVideoTitleTextField.h"
#import "VVideoUploadVC.h"

@interface VPreviewVC ()<VClipIndicatorViewDelegate>

@property(nonatomic, strong) AVPlayer *player;

@property(nonatomic, strong) UIView *navBar;

@property (nonatomic, assign) BOOL isAppear;

@property(nonatomic, strong) VClipIndicatorView *indicatorView;

@property(nonatomic, strong) UIImage *preImage;

@property(nonatomic, strong) VVideoTitleTextField *titleTextFile;

/**输入封面标题控件最大Y值*/
@property (nonatomic, assign) CGFloat titleTextFieldMaxY;

@end

@implementation VPreviewVC

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
    self.isAppear = YES;
    [self.player play];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.titleTextFieldMaxY = CGRectGetMaxY(self.titleTextFile.frame);
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
    self.isAppear = NO;
    [self.player pause];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor blackColor];
    [self setupPlayerWithURL:self.videoUrl];
    [self setupIndicator];
    [self setupNav];
    [self setupInputTitle];
    
    [self setupNatification];
    
}

- (void)setupPlayerWithURL:(NSURL *)url{
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:url];
    self.player = [[AVPlayer alloc] initWithPlayerItem:item];
    
    AVPlayerLayer *playLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    playLayer.frame = [UIScreen mainScreen].bounds;
    [self.view.layer addSublayer:playLayer];
    [self.player play];
}

- (void)setupIndicator{
    VClipIndicatorView *indicatorView = [[VClipIndicatorView alloc] initWithFrame:CGRectMake(16, [UIScreen mainScreen].bounds.size.height - 70, [UIScreen mainScreen].bounds.size.width - 32, 65)];
    self.indicatorView = indicatorView;
    indicatorView.isSelectCover = YES;
    indicatorView.asset = [AVAsset assetWithURL:self.videoUrl];
    indicatorView.delegate = self;
    [self.view addSubview:indicatorView];
}

- (void)setupNav{
    //标题栏容器
    UIView *navBar = [UIView new];
    self.navBar = navBar;
    navBar.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 64);
    [self.view addSubview: navBar];
    navBar.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.0];
    
    UIView *titleView = [UIView new];
    [navBar addSubview:titleView];
    titleView.frame = CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, 44);
    
    //标题
    UILabel *titleLabel = [UILabel new];
    titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [titleView addSubview:titleLabel];
    [[titleLabel.centerXAnchor constraintEqualToAnchor:titleView.layoutMarginsGuide.centerXAnchor] setActive:YES];
    [[titleLabel.centerYAnchor constraintEqualToAnchor:titleView.layoutMarginsGuide.centerYAnchor] setActive:YES];
    titleLabel.font = [UIFont systemFontOfSize:19];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.text = @"封面和标题";
    [titleLabel sizeToFit];
    
    //右边按钮
    UIButton *nextBtn = [UIButton new];
    [titleView addSubview:nextBtn];
    [nextBtn setTranslatesAutoresizingMaskIntoConstraints:NO];
    [[nextBtn.rightAnchor constraintEqualToAnchor:titleView.rightAnchor constant:-15] setActive:YES];
    [[nextBtn.centerYAnchor constraintEqualToAnchor:titleView.centerYAnchor constant:0] setActive:YES];
    [[nextBtn.widthAnchor constraintEqualToConstant:78] setActive:YES];
    [[nextBtn.heightAnchor constraintEqualToConstant:30] setActive:YES];
    nextBtn.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
    nextBtn.clipsToBounds = YES;
    nextBtn.layer.cornerRadius = 15;
    
    [nextBtn setTitle:@"发布" forState:UIControlStateNormal];
    nextBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    nextBtn.titleLabel.textColor = [UIColor whiteColor];
    [nextBtn setBackgroundColor:[UIColor orangeColor]];
    
    [nextBtn addTarget:self action:@selector(onCompleteClick) forControlEvents:UIControlEventTouchUpInside];
    
    //返回按钮
    UIButton *backBtn = [UIButton new];
    [backBtn setTranslatesAutoresizingMaskIntoConstraints:NO];
    [titleView addSubview:backBtn];
    [[backBtn.leftAnchor constraintEqualToAnchor:titleView.leftAnchor constant:5] setActive:YES];
    [[backBtn.centerYAnchor constraintEqualToAnchor:titleView.centerYAnchor] setActive:YES];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    backBtn.titleLabel.textColor = [UIColor whiteColor];
//    [backBtn setImage:[UIImage imageNamed:@"video_fanhui"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(onBackClick) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)setupInputTitle{
    VVideoTitleTextField *titleTextFile = [VVideoTitleTextField new];
    self.titleTextFile = titleTextFile;
    [self.view addSubview:titleTextFile];
    titleTextFile.translatesAutoresizingMaskIntoConstraints = NO;
    [[titleTextFile.leftAnchor constraintEqualToAnchor:self.view.leftAnchor constant:16] setActive:YES];
    [[titleTextFile.rightAnchor constraintEqualToAnchor:self.view.rightAnchor constant:-15] setActive:YES];
    [[titleTextFile.bottomAnchor constraintEqualToAnchor:self.indicatorView.topAnchor constant:-102] setActive:YES];
    
    titleTextFile.font = [UIFont systemFontOfSize:19];
    titleTextFile.titlePlaceHolder.text = @"请输入想说的话...";
    
}

- (void)setupNatification{
    //监听视频播放完成
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onfinishPlay) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toForground) name:UIApplicationWillEnterForegroundNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onkeyBoardChanged:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

#pragma mark - Action
- (void)onBackClick{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)onfinishPlay{
    [self.player seekToTime:kCMTimeZero];
    [self.player play];
}

- (void)onCompleteClick{
    VVideoUploadVC *vc = [VVideoUploadVC new];
    vc.image = self.preImage;
    vc.videoUrl = self.videoUrl;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - Notification
- (void)toBackground{
    if (self.isAppear) {
        [self.player pause];
    }
}

- (void)toForground{
    if (self.isAppear) {
        [self.player play];
    }
}

- (void)onkeyBoardChanged:(NSNotification *)notificaton{
    NSDictionary *dict = notificaton.userInfo;
    CGRect endFrame = [dict[UIKeyboardFrameEndUserInfoKey] CGRectValue];

    [UIView animateWithDuration:0.25 animations:^{
        if (self.titleTextFieldMaxY > endFrame.origin.y) {
            self.titleTextFile.transform = CGAffineTransformMakeTranslation(0, -(self.titleTextFieldMaxY - endFrame.origin.y + 10));
        }else{
            self.titleTextFile.transform = CGAffineTransformIdentity;
        }
    } completion:nil];
    
    
}

#pragma mark - VClipIndicatorViewDelegate
- (void)onSelectImage:(UIImage *)image{
    self.preImage = image;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    if ([[ NSFileManager defaultManager ] fileExistsAtPath :[VVideoClipManger shareClipManger].catchPath]) {
        [[NSFileManager defaultManager] removeItemAtPath:[VVideoClipManger shareClipManger].catchPath error:nil];
    }
}

@end
